// ceremonyHall.js
const { runAsync, allAsync, getAsync, retryOperation, log } = require('./dbConfig'); // 导入全局工具

/**
 * 新增仪式厅
 * @param {Object} req - 请求对象，包含仪式厅信息
 * @param {Object} res - 响应对象
 */
const addCeremonyHall = async (req, res) => {
  const { partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr, remarks, ceremony_hall_img, create_user } = req.body;
  if (!ceremony_hall_name) {
    return res.status(500).json({ success: false, msg: '仪式厅名称为必填项', code: '1', data: [] });
  }

  try {
    await retryOperation(() =>
      runAsync(
        `INSERT INTO sk_ceremony_hall (partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr, remarks, ceremony_hall_img, create_user) VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr, remarks, ceremony_hall_img, create_user]
      )
    );
    const result = await getAsync(`SELECT last_insert_rowid() as id`);
    const lastID = result.id;
    log(`Inserted ID: ${lastID}`);
    res.json({ success: true, msg: '新增成功', code: '0', data: [lastID] });
  } catch (err) {
    log(`新增仪式厅失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '新增仪式厅信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 修改仪式厅信息
 * @param {Object} req - 请求对象，包含更新信息和 ID
 * @param {Object} res - 响应对象
 */
const updateCeremonyHall = async (req, res) => {
  const { id, partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr, remarks, ceremony_hall_img, update_user } = req.body;

  try {
    await retryOperation(() =>
      runAsync(
        `UPDATE sk_ceremony_hall SET partner_company_id = ?, partner_company_name = ?, ceremony_hall_name = ?, ceremony_hall_addr = ?, remarks = ?, ceremony_hall_img = ?, update_user = ?, update_time = CURRENT_TIMESTAMP WHERE id = ? AND del_flag = '0'`,
        [partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr, remarks, ceremony_hall_img, update_user, id]
      )
    );
    res.json({ success: true, msg: '修改成功', code: '0', data: [] });
  } catch (err) {
    log(`修改仪式厅失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '修改仪式厅信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 删除仪式厅（逻辑删除）
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const deleteCeremonyHall = async (req, res) => {
  const { id } = req.params;

  try {
    // 校验是否存在d档期信息
    const schedule = await allAsync(
      `SELECT * FROM sk_schedule WHERE ceremony_hall_id = ? AND del_flag = '0'`,
      [id]
    );
    if (schedule.length > 0) {
      return res.status(500).json({
        success: false,
        msg: '仪式厅下存在档期信息，请先调整档期信息',
        code: '1',
        data: []
      });
    }
    await retryOperation(() =>
      runAsync(`UPDATE sk_ceremony_hall SET del_flag = '1' WHERE id = ?`, [id])
    );
    res.json({ success: true, msg: '删除成功', code: '0', data: [] });
  } catch (err) {
    log(`删除仪式厅失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '删除仪式厅信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 查询仪式厅列表（带搜索条件和分页）
 * @param {Object} req - 请求对象，包含搜索条件和分页参数
 * @param {Object} res - 响应对象
 */
const getPageCeremonyHallList = async (req, res) => {
  const { partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr, page, size } = req.query;

  const pageNum = parseInt(page) || 1; // 默认第 1 页
  const pageSize = parseInt(size) || 10; // 默认每页 10 条

  let query = 'SELECT * FROM sk_ceremony_hall WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_ceremony_hall WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (partner_company_id) {
    query += ' AND partner_company_id = ?';
    countQuery += ' AND partner_company_id = ?';
    params.push(partner_company_id);
    countParams.push(partner_company_id);
  }

  if (partner_company_name) {
    query += ' AND partner_company_name LIKE ?';
    countQuery += ' AND partner_company_name LIKE ?';
    params.push(`%${partner_company_name}%`);
    countParams.push(`%${partner_company_name}%`);
  }

  if (ceremony_hall_name) {
    query += ' AND ceremony_hall_name LIKE ?';
    countQuery += ' AND ceremony_hall_name LIKE ?';
    params.push(`%${ceremony_hall_name}%`);
    countParams.push(`%${ceremony_hall_name}%`);
  }

  if (ceremony_hall_addr) {
    query += ' AND ceremony_hall_addr LIKE ?';
    countQuery += ' AND ceremony_hall_addr LIKE ?';
    params.push(`%${ceremony_hall_addr}%`);
    countParams.push(`%${ceremony_hall_addr}%`);
  }

  query += ' ORDER BY id DESC LIMIT ? OFFSET ?';
  params.push(pageSize, (pageNum - 1) * pageSize);

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`Get ceremony hall list error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

/**
 * 查询仪式厅列表（带搜索条件不分页）
 * @param {Object} req - 请求对象，包含搜索条件
 * @param {Object} res - 响应对象
 */
const getCeremonyHallList = async (req, res) => {
  const { partner_company_id, partner_company_name, ceremony_hall_name, ceremony_hall_addr } = req.query;
  let query = 'SELECT * FROM sk_ceremony_hall WHERE del_flag = \'0\'';
 let countQuery = 'SELECT COUNT(*) as total FROM sk_ceremony_hall WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (partner_company_id) {
    query += ' AND partner_company_id = ?';
    countQuery += ' AND partner_company_id = ?';
    params.push(partner_company_id);
    countParams.push(partner_company_id);
  }

  if (partner_company_name) {
    query += ' AND partner_company_name LIKE ?';
    countQuery += ' AND partner_company_name LIKE ?';
    params.push(`%${partner_company_name}%`);
    countParams.push(`%${partner_company_name}%`);
  }

  if (ceremony_hall_name) {
    query += ' AND ceremony_hall_name LIKE ?';
    countQuery += ' AND ceremony_hall_name LIKE ?';
    params.push(`%${ceremony_hall_name}%`);
    countParams.push(`%${ceremony_hall_name}%`);
  }

  if (ceremony_hall_addr) {
    query += ' AND ceremony_hall_addr LIKE ?';
    countQuery += ' AND ceremony_hall_addr LIKE ?';
    params.push(`%${ceremony_hall_addr}%`);
    countParams.push(`%${ceremony_hall_addr}%`);
  }

  query += ' ORDER BY id DESC';

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`获取仪式厅信息列表失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '获取仪式厅列表失败，请刷新重试', code: '1', data: [] });
  }
};

/**
 * 查询仪式厅详情
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const queryCeremonyHallDetail = async (req, res) => {
  const { id } = req.params;

  try {
    const row = await getAsync('SELECT * FROM sk_ceremony_hall WHERE id = ? AND del_flag = \'0\'', [id]);
    if (!row) {
      return res.status(500).json({ success: false, msg: '未查询到仪式厅信息', code: '1', data: [] });
    }
    res.json({ data: row, code: '0', success: true, msg: '查询详情成功' });
  } catch (err) {
    log(`Get ceremony hall detail error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

// 模块导出
module.exports = { addCeremonyHall, updateCeremonyHall, deleteCeremonyHall, getPageCeremonyHallList, getCeremonyHallList, queryCeremonyHallDetail };